<?php

namespace App\Backend\Service;

use App\Models\Comment;
use App\Exceptions\InvalidRequestException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Backend\Service\BaseService;
use App\Http\Service\UserService;
class CommentService extends BaseService
{

    private $model;

    public function __construct(Comment $model,UserService $userService)
    {
        parent ::__construct();
        $this->model = $model;
        $this->userService=$userService;
    }

    # 列表
    public function getList($request,$data=[])
    {
        $page = intval($request->json('page')) ?: $this->cpage;
        $limit = intval($request->json('limit')) ?: $this->climit;
        $offset = ($page - 1) * $limit;

        $type = $data['type'] ?? '2'; // 添加默认值防止未定义错误

        // 构建基础查询条件
        $baseWhere = [
           
        ];

        
        //dd($baseWhere);

        // 根据类型设置不同的查询
        if ($type == '1') {
            # 爆料
            $where = array_merge($baseWhere, [['A.type', '=', '2']]);
            $fields = ['A.id', 'A.people_id', 'A.content', 'A.images', 'A.address', 'A.create_time', 'A.update_time', 'B.title', 'B.product_id', 'B.cover'];
             // 构建查询
            $query = $this->model->select($fields)
                ->from('comment as A')
                ->join('baoliao_post as B', 'A.unique_id', '=', 'B.unique_id')
                ->where($where);

        } else {
            # 逛逛
            $where = array_merge($baseWhere, [['A.type', '=', '1']]);
            $fields = ['A.id', 'A.people_id', 'A.content', 'A.images', 'A.address', 'A.create_time', 'A.update_time', 'B.title', 'C.product_id', 'C.cover'];
             // 构建查询
            $query = $this->model->select($fields)
                ->from('comment as A')
                ->join('douban_post as B', 'A.unique_id', '=', 'B.unique_id')
                ->join('douban_post_product as  C', 'A.unique_id', '=', 'C.post_unique_id')
                ->where($where);
        }

        // 关键词搜索条件 - 修复版本
        if (isset($data['keyword']) && !empty(trim($data['keyword']))) {
            $keyword = trim($data['keyword']);
            // 直接构建where条件，不使用匿名函数
            $baseWhere[] = function($query) use ($keyword) {
                $query->where('A.content', 'like', "%{$keyword}%")
                      ->orWhere('A.nickname', 'like', "%{$keyword}%");
            };
        }

        // 获取总数
        $count = $query->count();

        // 获取分页数据
        $list = $query->orderBy('A.update_time', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();

        // 处理用户信息
        foreach ($list as $k => &$v) {
            //dd($v);
            $people_id = $v['people_id'];
            $userdata = $this->userService->update_user($people_id);
            $v['nickname'] = $userdata['nickname'] ?? '';
            $v['avatar'] = $userdata['avatar'] ?? '';
            if(isset($v['images'])){
                $v['images']=json_decode($v['images'],true);
            }else{
                $v['images']=[];
            }

        }

        $result = [
            'page' => $page,
            'limit' => $limit,
            'total_page' => ceil($count / $limit),
            'count' => $count,
            'data' => $list
        ];

        return $result;

    }
      /**
     * 添加
     */
    public function add($request,$data)
    {
        $where=[
            'original_name'=>$data['original_name'],
            'standard_name'=>$data['standard_name'],
        ];
        $first=$this->model->where($where)->first();
        if($first){
            $data['create_time'] =date("Y-m-d H:i:s");
            $this->model->where($where)->update($data);
        }else{
            $data['create_time'] =date("Y-m-d H:i:s");
            $data['update_time'] =date("Y-m-d H:i:s");

            $res=$post_id=$this->model->insertGetId($data);
        }
    }
    /**
     * 编辑
     */
    public function edit($request,$data,$id)
    {
        $res = $this->model->where('id',$id)->first();
        if(!$res) {
            $this->error('内容不存在');
        }
        
        $data['update_time'] = date("Y-m-d H:i:s");

        $res =  $this->model->where('id',$id)->update($data);
        if(!$res){
            $this->error('修改失败');
        }else{
            $this->success();
        }
    }   

     /**
     * 删除
     */
    public function del($ids)
    {
        $res =  $this->model->whereIn('id',$ids)->delete();
        if(!$res){
            $this->error('删除失败');
        }else{
            $this->success();
        }
    }   
    


}
